# app/api/routes/auth.py
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer
from sqlalchemy.orm import Session
from datetime import timedelta
from typing import List, Optional

from app.core.database import get_db
from app.core.config import settings
from app.models import models
from app.schemas import schemas
from app.crud import crud
from app.auth.auth import (
    create_access_token,
    authenticate_user,
    invalidate_token,
    verify_token,
)

router = APIRouter()
security = HTTPBearer()

# 依赖函数
def get_current_user(db: Session = Depends(get_db), token=Depends(security)):
    from jose import JWTError, jwt

    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
    )
    try:
        payload = jwt.decode(
            token.credentials, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
        )
        username: Optional[str] = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception

    user = crud.get_user_by_username(db, username=username)
    if not verify_token(token.credentials):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户已注销",
        )
    if user is None:
        raise credentials_exception
    return user

@router.post("/login", response_model=schemas.Token)
def login(user_data: schemas.UserLogin, db: Session = Depends(get_db)):
    user = authenticate_user(db, user_data.username, user_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
        )
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {
        "username": user.username,
        "expires": access_token_expires,
        "access_token": access_token,
        "token_type": "bearer",
    }

@router.post("/logout")
def logout(user_data: schemas.UserLogout, db: Session = Depends(get_db)):
    invalidate_token(user_data.access_token)
    return {"status": "success", "message": "注销成功"}

@router.post("/register")
def register(user_data: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = crud.get_user_by_username(db, username=user_data.username)
    if db_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    return crud.create_user(db=db, user=user_data)